<?php
/**
 * Created by PhpStorm.
 * User: shaowei
 * Date: 2018/12/21
 * Time: 上午11:23
 */

namespace App\Http\Model;

use Illuminate\Support\Arr;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Redis;


class System extends Base
{
    // 默认系统配置表 或系统版本表:system_version
    public $table = 'system_config';
    public $tableAlert = 'system_alert';
    public $tableAsaReport = 'asa_report';
    public $table_system_nav_menu = 'system_nav_menu';

    private $redis_cache_system_config = "CACHE:SYSTEM:CONFIG";
    private $redis_cache_system_expression = "CACHE:SYSTEM:EXPRESSION";
    private $redis_cache_system_expression_new = "CACHE:SYSTEM:EXPRESSION:NEW";
    private $redis_cache_system_version = "CACHE:SYSTEM:VERSION";

    private $cacheSystemFullScreenHash = 'CACHE:SYSTEM:FULLSCREEN:HASH';

    // 图片验证码
    public $redisKeyPhoneCaptchaCode = 'CACHE:SYSTEM:PHONE:CAPTCHA_CODE:';
    // 操作手机号时间
    public $redisKeyOpPhoneTime = 'CACHE:SYSTEM:PHONE:TIME:';

    private $redis_cache_system_explain = "CACHE:SYSTEM:EXPLAIN:"; //说明文字

    private $cacheSystemAlertHash = 'CACHE:SYSTEM:ALERT:HASH';

    private $redis_system_nav_menu = 'SYSTEM:NAV:MENU';
    private $redis_room_fast_msg = 'SYSTEM:ROOM:FAST:MSG';

    //审核相关
    private $redis_examine_switch = 'EXAMINE:SWITCH';
    private $redis_examine_room_notice = 'EXAMINE:ROOM:NOTICE';
    private $redis_examine_trends_id = 'EXAMINE:TRENDS:ID';

    public function __construct(array $attributes = [])
    {
        parent::__construct($this->table, $attributes);
    }

    /**
     * 获取最后版本信息
     * @param $platform_id
     * @param $channel_id
     * @return mixed
     */
    public function get_last_version($platform_id, $channel_id){
//        $data = Redis::HGET($this->redis_cache_system_version, $platform_id . '-' . $channel_id);

        if (!empty($data)){
            return json_decode($data, true);
        }
        $version_item = DB::table("system_version")
                  ->where("platform_id", $platform_id)
//                  ->where("channel_id", $channel_id)
                  ->orderBy("id", "desc")
                  ->first(["version_id", "describe", "platform_id", "download_url", "channel_id", "upgrade_type"]);

        if(empty($version_item)){
            return null;
        }
        $result = self::objToArray($version_item);
        if (!empty($result['download_url'])){
            if (strlen($result['download_url']) >= 4 && substr($result['download_url'],0,4) != 'http'){
                $result['download_url'] = getPicDomain() . $result['download_url'];
            }
        }

        Redis::HSET($this->redis_cache_system_version, $platform_id . '-' . $channel_id, json_encode($result));
        if(Redis::TTL($this->redis_cache_system_version) == -1){
            Redis::EXPIRE($this->redis_cache_system_version, 3600);
        }
        return $result;
    }

    public function get_version($id){
        $version_item = DB::table("system_version")
            ->where("id", $id)
            ->first(["version_id", "describe", "platform_id", "download_url", "channel_id", "upgrade_type"]);

        if(empty($version_item)){
            return null;
        }
        $result = self::objToArray($version_item);
        $result['download_url'] = getPicDomain() . $result['download_url'];
        return $result;
    }

    public function get_audit_switch(string $version_id,int $platform_id,int $channel_id){
        $audit_switch = Redis::HGET($this->redis_cache_system_version, "AW-".$version_id.'-'.$platform_id . '-' . $channel_id);
        if($audit_switch) {
            return intval($audit_switch);
        }

        $result = DB::table("system_version")
            ->where(['version_id' => $version_id,'platform_id' => $platform_id,'channel_id' => $channel_id])
            ->first(['audit_switch']);
        $audit_switch = 0;
        if (!empty($result)){
            $audit_switch = $result->audit_switch;
        }
        Redis::HSET($this->redis_cache_system_version,"AW-".$version_id.'-'.$platform_id . '-' . $channel_id, $audit_switch);
        if(Redis::TTL($this->redis_cache_system_version) == -1){
            Redis::EXPIRE($this->redis_cache_system_version, 3600);
        }
        return intval($audit_switch);
    }



    /**
     * 获取表情最后版本
     * @return mixed|null
     */
    public function get_expression_last_version(){
        $data = Redis::GET($this->redis_cache_system_expression);
        if (!empty($data)){
            return json_decode($data, true);
        }
        $version_item = DB::table("system_expression")
            ->where("version", 9)
            ->first(["version", "download_url", "md5"]);
        if(empty($version_item)){
            return null;
        }
        $result = self::objToArray($version_item);
        $result['download_url'] = getPicDomain() . $result['download_url'];
        Redis::SET($this->redis_cache_system_expression, json_encode($result));
        Redis::EXPIRE($this->redis_cache_system_expression, 3600);
        return $result;
    }

    /**
     * 获取表情最后版本
     * @return mixed|null
     */
    public function get_expression_new_last_version(){
        $data = Redis::GET($this->redis_cache_system_expression_new);
        if (!empty($data)){
            return json_decode($data, true);
        }
        $version_item = DB::table("system_expression")
            ->orderBy("version", "desc")
            ->first(["version", "download_url", "md5"]);
        if(empty($version_item)){
            return null;
        }
        $result = self::objToArray($version_item);
        $result['download_url'] = getPicDomain() . $result['download_url'];
        Redis::SET($this->redis_cache_system_expression_new, json_encode($result));
        Redis::EXPIRE($this->redis_cache_system_expression_new, 3600);
        return $result;
    }

    public function get_config(){
        $data = Redis::HGETALL($this->redis_cache_system_config);
        $all_data = [];
        if (!empty($data)){
            foreach ($data as $k => $v){
                $all_data[$k] = json_decode($v, true);
            }
            return $all_data;
        }
        $result = DB::table("system_config")->get();
        if(empty($result)){
            return null;
        }
        $result = self::objToArray($result);
        $all_data = [];
        $ret_data = [];
        foreach ($result as $k => $v){
            $all_data[$v['key']] = json_encode($v);
            $ret_data[$v['key']] = $v;
        }
        Redis::HMSET($this->redis_cache_system_config, $all_data);
        Redis::EXPIRE($this->redis_cache_system_config, 3600);
        return $ret_data;
    }

    /**
     * 清除缓存
     * @param int $type
     */
    public function clear_cache(int $type = 1){
        $redis_key = null;
        if($type === 1){
            $redis_key = $this->redis_cache_system_config;
        } elseif ($type === 2){
            $redis_key = $this->redis_cache_system_version;
        }

        Redis::DEL($redis_key);
    }


    public function getSystemVersion($condition=[]){
        $result = DB::table("system_version")->where($condition)->first();
        return self::objToArray($result);
    }

    /**
     * 客服列表
     * @param int $type 默认 0; 1 客服; 2 运营
     * @return \Illuminate\Support\Collection
     */

    public function getCustomer(int $type = 0) {
        $query = DB::table('system_customer');
        if($type > 0) {
            $query = $query->where('type', $type);
        }
        return $query->get(['mobile_phone','customer_name'])
            ->toArray();

    }

    ################# 统一图形验证码模块 ##########################################

    /**
     * 保存图形验证码
     *
     * @param string $phone 手机号
     * @param string $code 验证码
     * */
    public function storeCaptchaCode($phone, $code)
    {
        Redis::setex($this->redisKeyPhoneCaptchaCode . $phone, 180, $code);
    }

    /**
     * 校验图形验证码
     *
     * @param string $phone 手机号
     * @param string $code 验证码
     * @param int $isDeleteCodeState 是否删除验证码状态（0=不删除验证码 1=删除验证码）
     * @return bool
     * */
    public function checkCaptchaCode($phone, $code, $isDeleteCodeState)
    {
        $captchaCode = Redis::get($this->redisKeyPhoneCaptchaCode . $phone);

        // 函数 strncasecmp()
        // 0 - 如果两个字符串相等
        // < 0 - 如果 string1 小于 string2
        // > 0 - 如果 string1 大于 string2

        if (empty($captchaCode) or strncasecmp($code, $captchaCode, 4) != 0) return false;

        // 删除图形验证码
        if ($isDeleteCodeState) Redis::del($this->redisKeyPhoneCaptchaCode . $phone);

        return true;
    }

    /**
     * 记录操作手机号时间
     *
     * @param string $phone 手机号
     * */
    public function recordPhoneOpTime($phone)
    {
        Redis::setex($this->redisKeyOpPhoneTime . $phone, 3600 * 3, time());
    }

    /**
     * 检验是否存在手机号操作时间
     *
     * @param string $phone 手机号
     * @return bool
     * */
    public function checkRecordPhoneOpTime($phone)
    {
        if (!Redis::exists($this->redisKeyOpPhoneTime . $phone)) return false;

        return true;
    }


    /**
     * 获取全服飘屏信息
     * @param $id
     */
    public function getFullScreen($id){
	    $cacheData = Redis::HGET($this->cacheSystemFullScreenHash, $id);
	    $cacheData = [];
        if (!empty($cacheData)){
            return json_decode($cacheData, true);
        }
        $result = DB::table('system_full_screen')->get();
        $result = $this->objToArray($result);
        $result = array_column($result, null, 'id');
        foreach ($result as $k => $v){
            if (!empty($v['bg_img_url'])){
                $result[$k]['bg_img_url'] = getPicDomain() . $v['bg_img_url'];
            }
            if (!empty($v['action_img_url'])){
                $result[$k]['action_img_url'] = getPicDomain() . $v['action_img_url'];
            }
            Redis::HSET($this->cacheSystemFullScreenHash, $k, json_encode($result[$k]));
        }
        Redis::EXPIRE($this->cacheSystemFullScreenHash, 3600);
        if(!array_key_exists($id, $result)){
            return null;
        }
        return $result[$id];
    }

    /**获取系统说明信息
     * @return array|null
     */
    public function getExplain($type,$key){
        $all_data = Redis::HGETALL($this->redis_cache_system_explain.$type);
        if(empty($all_data)){
            $data = DB::table("system_explain")->where('type',$type)->get();
            $data = self::objToArray($data);
            $all_data = [];
            foreach ($data as &$v){
                $all_data[$v['key']] = json_encode($v);
            }
            if(!empty($all_data)){
                Redis::HMSET($this->redis_cache_system_explain.$type, $all_data);
                Redis::EXPIRE($this->redis_cache_system_explain.$type, 3600);
            }
        }
        foreach ($all_data as &$d){
            if(!is_array($d)){
                $d = json_decode($d,true);
            }
        }
        if($key == 'all'){
            return  $all_data;
        }
        return $all_data[$key];
    }

    /**
     * 删除缓存
     *
     * Created at 2021/12/23 16:49
     * @Author <yuxiang.zhu@asiainnovations.net>
     * @param $type
     * @return bool
     */
    public function deleteExplainCache(int $type)
    {
        Redis::DEL($this->redis_cache_system_explain . $type);
        return true;
    }

    public function get_system_alert($id){
        $cacheData = Redis::HGET($this->cacheSystemAlertHash, $id);
        if (!empty($cacheData)){
            return json_decode($cacheData, true);
        }
        $result = DB::table($this->tableAlert)->get();
        $result = $this->objToArray($result);
        $result = array_column($result, null, 'id');
        foreach ($result as $k => $v){
            Redis::HSET($this->cacheSystemAlertHash, $k, json_encode($result[$k]));
        }
        Redis::EXPIRE($this->cacheSystemAlertHash, 3600);
        if(!array_key_exists($id, $result)){
            return null;
        }
        return $result[$id];
    }

    /**获取底部导航资源
     * @param $key
     * @return array|mixed
     */
    public function getNavMenuRes(){
        $res = Redis::get($this->redis_system_nav_menu);
        return empty($res) ? [] : json_decode($res,true);
    }

    /**
     * 获取房间快捷消息文本
     * @return false|string[]
     */
    public function getRoomFastMsg()
    {
        $res = Redis::get($this->redis_room_fast_msg);
        if (!$res) {
            return ["耶斯莫拉", "什么是快乐星球", "达咩  达咩", "针不戳", "这个怎么玩"];
        }

        return explode(',', $res);
    }

    /**获取审核开关
     * @param $key
     * @return int|string
     */
    public function getExamineSwitch($key){
        $res = 0;
        switch ($key){
            case 'switch':
                $res = Redis::get($this->redis_examine_switch) ?? 0;
                break;
            case 'notice':
                $res = Redis::get($this->redis_examine_room_notice) ?? '';
                break;
            case 'trends':
                $res = Redis::get($this->redis_examine_trends_id) ?? 0;
                break;
        }
        return $res;
    }

    public function createAsaReport(array $data = []) {
        return DB::table($this->tableAsaReport)->insertGetId([
            'code' => $data['code'] ?? '',
            'idfa' => $data['idfa'] ?? '',
            'paras' => $data['paras'] ? json_encode($data['paras']) : '',
            'is_iad' => $data['is_iad'] ?? 0,
            'create_time' => time(),
            'iad_purchase_date' => $data['iad_purchase_date'],
            'iad_keyword' => $data['iad_keyword'],
            'iad_adgroup_id' => $data['iad_adgroup_id'],
            'iad_campaign_id' => $data['iad_campaign_id'],
            'iad_lineitem_id' => $data['iad_lineitem_id'],
            'iad_conversion_date' => $data['iad_conversion_date'],
            'iad_org_id' => $data['iad_org_id'],
            'iad_keyword_id' => $data['iad_keyword_id'],
            'iad_conversion_type' => $data['iad_conversion_type'],
            'iad_country_or_region' => $data['iad_country_or_region'],
            'iad_org_name' => $data['iad_org_name'],
            'iad_campaign_name' => $data['iad_campaign_name'],
            'iad_click_date' => $data['iad_click_date'],
            'iad_attribution' => $data['iad_attribution'],
            'iad_adgroup_name' => $data['iad_adgroup_name'],
            'iad_keyword_matchtype' => $data['iad_keyword_matchtype'],
            'iad_lineitem_name' => $data['iad_lineitem_name'],
            'guid' => $data['guid']
        ]);
    }

    /**
     * 是否苹果上报
     */
    public function isAppleReort(string $guid) {
        return DB::table($this->tableAsaReport)
        ->where('guid', $guid)
        ->where('iad_attribution', 'true')
        ->count();
    }
    /**
     * 获取苹果上报信息
     */
    public function appleReortInfo(string $guid) {
        return DB::table($this->tableAsaReport)
            ->where('guid', $guid)
            ->orderBy('id','desc')
            ->where('iad_attribution', 'true')
            ->first();
    }

    private $redis_cache_system_device_risk = "CACHE:SYSTEM:DEVICE_RISK";
    public function deviceRiskQueue(array $data = [])
    {
        Redis::RPUSH($this->redis_cache_system_device_risk, json_encode($data));
    }

    public function getDeviceRiskQueue()
    {
        return Redis::LPOP($this->redis_cache_system_device_risk);
    }

    /**
     * 清理缓存
     */
    public function clearSystemConfigCache()
    {
        Redis::del($this->redis_cache_system_config);
    }

    public function findNavByKey($key){
        $res = DB::connection($this->connection)->table($this->table_system_nav_menu)
            ->where('key',$key)
            ->first();
        return $this->objToArray($res);
    }
    public function addNavMenu(array $data){
        $data['created_at'] = time();
        $data['updated_at'] = time();
        return DB::connection($this->connection)->table($this->table_system_nav_menu)
            ->insert($data);
    }
    public function updateNavMenu($id , array $data){
        $data['updated_at'] = time();
        return DB::connection($this->connection)->table($this->table_system_nav_menu)
            ->where('id',$id)
            ->update($data);
    }
    public function navList(){
        return [
            ['key'=> 'matchingIcon' , 'desc' => '匹配'],
            ['key'=> 'activeIcon' , 'desc' => '动态'],
            ['key'=> 'recreateIcon' , 'desc' => '娱乐'],
            ['key'=> 'messageIcon' , 'desc' => '消息'],
            ['key'=> 'myIcon' , 'desc' => '我的'],
            ['key'=> 'refreshIcon' , 'desc' => '刷新']
        ];
    }

    public function setNavMenuRedis() {
        $keysArr = array_column($this->navList(),'key');
        $data = DB::connection($this->connection)->table($this->table_system_nav_menu)
            ->whereIn('key' ,$keysArr)
            ->select(['key','value'])
            ->get();
        $data = array_column($this->objToArray($data),'value','key');
        $redisDataArr = [];
        foreach ($keysArr as $key){
            $redisDataArr[$key] = isset($data[$key])?build_url('/'.$data[$key]):'';
        }
        $redisData = json_encode(array_values($redisDataArr));
        $res = Redis::set($this->redis_system_nav_menu,$redisData);
        return $res;

    }
    /**
     * 获取渠道推荐的房间
     */
    public function getRoomRocketSwitch()
    {
        $key = 'room_rocket_switch';
        $data = [];
        $configs = $this->get_config() ?: [];

        if (isset($configs[$key]) && $val = $configs[$key]['value']) {
            $data = json_decode($val, true) ?? [];
        }
        return (array)$data;
    }

    public function delNavMenu($id){
        return DB::table($this->table_system_nav_menu)->where('id',$id)->delete();
    }

    /**
     * 获取渠道推荐的房间
     * 配置的是room_uid
     */
    public function getChannelRecommendedRoom()
    {
        $key = 'special_channel_recommended_room';
        $data = [];
        $configs = $this->get_config() ?: [];

        if (isset($configs[$key]) && $val = $configs[$key]['value']) {
            $data = json_decode($val, true) ?? [];
        }
        return (array)$data;
    }

    /**
     * 获取推荐置顶的房间
     */
    public function getRecommendTopRoomUids()
    {
        $key = 'recommend_top_room';
        $data = [];
        $configs = $this->get_config() ?: [];

        if (isset($configs[$key]) && $val = $configs[$key]['value']) {
            $data = json_decode($val, true) ?? [];
        }
        return (array)$data;
    }

    public function getHideRanking(){
        $key = 'hide_ranking';
        $configs = $this->get_config() ?: [];
        if (isset($configs[$key]) && $configs[$key]['value'] == 1) {
            return true;
        }
        return false;
    }

    //读取测试货架配置room_uid列表
    public function getTestCounterRoomUids(){
        $key = 'test_counter_room_list';
        $configs = $this->get_config() ?: [];
        if (empty($configs[$key]['value'])) {
            return [];
        }
        $roomUids = explode(',',$configs[$key]['value']);
        return  array_map('intval' , $roomUids);
    }
    /**
     * 获取以json格式存储的指定资源
     */
    public function getJsonArrConfigByStr($key)
    {
        $data = [];
        $configs = $this->get_config() ?: [];

        if (isset($configs[$key]) && $val = $configs[$key]['value']) {
            $data = json_decode($val, true) ?? [];
        }
        return (array)$data;
    }
    /**
     * 获取盛付通支付配置
     * @return array
     */
    public function getPaySftConfig(): array
    {
        $key = 'pay_sft';
        $configs = $this->getDefaultSystemConfig();
        return isset($configs[$key]) ? explode(',', $configs[$key]['value']) : [];
    }

    /**
     * 获取百富支付配置
     * @return array
     */
    public function getPayWeibaoConfig(): array
    {
        $key = 'pay_weibao';
        $configs = $this->getDefaultSystemConfig();
        return isset($configs[$key]) ? explode(',', $configs[$key]['value']) : [];
    }
    /**
     * 获取支付等级配置
     * @return array
     */
    public function getPaylevelConfig($key)
    {

        $key = empty($key)?'pay_level_v1':$key;
        $configs = $this->get_config() ?: [];;
        return isset($configs[$key]) ? explode(',', $configs[$key]['value']) : [];
    }

    /**
     * 获取注册用户天数金额显示限制
     * @param $key
     * @return void
     */
    public function getPayRegisterTimeMoneyConfig($key)
    {
        $key = empty($key)?'pay_register_time_money':$key;
        $configs = $this->get_config() ?: [];
        return isset($configs[$key]) ? explode(',', $configs[$key]['value']) : [7,1000];
    }
}
